import { Service } from "egg";
import * as crypto from "crypto";
/**
 * 微信支付分(V3)升级之后
 * @description  此类用来操作微信支付分API
 * @author CCJ
 */
export default class PayUtils extends Service {
  // 验证MD5签名
  public verifySign(params: any, key: string): boolean {
    if (!params.sign) {
      return false;
    }
    const sign = params.sign;
    delete params.sign;
    const paySign = this.generateSign(params, key);
    return sign === paySign;
  }

  // 生成签名
  public generateSign(params: any, key: string, algorithm = "md5", keyName = "key"): string {
    const signStr = `${this.sortParams(params)}&${keyName}=${key}`;
    // console.log("signStr", signStr);
    const md5 = crypto.createHash(algorithm);
    md5.update(signStr);
    return md5.digest("hex").toUpperCase();
  }

  // 生成签名
  public sha1(signStr: any): string {
    const sha1 = crypto.createHash("sha1");
    sha1.update(signStr);
    return sha1.digest("hex");
  }

  // 排序参数
  sortParams(args) {
    let keys = Object.keys(args);
    keys = keys.sort();
    const newArgs = {};
    keys.forEach((key) => {
      newArgs[key] = args[key];
    });
    let string = "";
    for (const k in newArgs) {
      string += "&" + k + "=" + newArgs[k];
    }
    string = string.substr(1);
    return string;
  }

  /**
   * 生成随机字符串
   * @param length 生成的长度
   */
  public makeNonceStr(length: number) {
    let nonceStr = "";
    const chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
    const maxPos = chars.length;
    for (let index = 0; index < length; index++) {
      nonceStr += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return nonceStr;
  }

  /**
   * 生成一个签名
   * @param alg 算法
   * @param privateKey 密钥
   * @param signStr 签名字符串
   */
  public signBase64(alg: string, privateKey: any, signStr): string {
    const sign = crypto.createSign(alg);
    sign.update(signStr);
    return sign.sign(privateKey, "base64");
  }
}
